package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.gson
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.zoneOffset
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.HmacAlgorithms
import org.apache.commons.codec.digest.HmacUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.time.LocalDateTime
import java.util.*

@Component
class WphClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://vop.vipapis.com"

    fun execute(store: Store, method: String, request: Map<String, Any>): JsonObject {
        val authorization = store.authorization
        val signMap = TreeMap<String, Any>()
        signMap["service"] = "vipapis.marketplace.delivery.SovDeliveryService"
        signMap["method"] = method
        signMap["version"] = "1.0.0"
        signMap["timestamp"] = LocalDateTime.now().toEpochSecond(zoneOffset)
        signMap["format"] = "json"
        signMap["appKey"] = authorization["appKey"]
        signMap["accessToken"] = authorization["accessToken"]
        val sysParams = signMap.entries.joinToString("") { it.key + it.value }
        val appParams = gson.toJson(request)
        val sign = HmacUtils(HmacAlgorithms.HMAC_MD5, authorization["appSecret"])
            .hmacHex(sysParams + appParams)
            .uppercase()

        val builder = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .queryParam("sign", sign)
        signMap.forEach { builder.queryParam(it.key, it.value) }

        val headers = HttpHeaders()
        headers["Content-Type"] = "application/json;charset=UTF-8"
        val requestEntity = HttpEntity<Any>(appParams, headers)
        val url = builder.build(false).toUriString()
        return restTemplate.exchange(url, HttpMethod.POST, requestEntity, String::class.java)
            .body!!
            .toJsonObject()
    }
}